package org.csu.jpetstore_users_backend_pj.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csu.jpetstore_users_backend_pj.result.CommonResponse;
import org.csu.jpetstore_users_backend_pj.result.ResponseCode;
import org.csu.jpetstore_users_backend_pj.service.CartService;
import org.csu.jpetstore_users_backend_pj.service.CatalogService;
import org.csu.jpetstore_users_backend_pj.service.InventoryService;
import org.csu.jpetstore_users_backend_pj.vo.CartItemVO;
import org.csu.jpetstore_users_backend_pj.vo.CartVO;
import org.csu.jpetstore_users_backend_pj.vo.ItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/carts/{username}")
@CrossOrigin(origins = "http://localhost:5173")
public class CartController {
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private CartService cartService;
    @Autowired
    private CatalogService catalogService;
    private Map<String, Object> claims;

    @GetMapping
    public CommonResponse viewCart(@PathVariable String username) {
        CartVO cartVO = cartService.getCart(username);
        if(cartVO==null){
            cartVO=new CartVO();
        }
//        System.out.println(cartVO);
        return CommonResponse.createForSuccess(ResponseCode.GetCartSuccess.getCode(),ResponseCode.GetCartSuccess.getDescription(),cartVO);
    }

    @PostMapping
    public CommonResponse addItemToCart(@RequestParam String workingItemId,
                                        @PathVariable String username){
        System.out.println("添加物品"+"workingItemId:"+workingItemId);
        CartVO cart = cartService.getCart(username);
        if (cart == null){
            cart = new CartVO();
        }
        if (cart.containsItemId(workingItemId)) {
            // 在加数量之前先检测库存
            if (inventoryService.getInventoryByItemId(workingItemId) <= 0) {
                return CommonResponse.createForError(ResponseCode.InventoryShortageSuccess.getCode(), "库存不足，无法继续添加");
            }
            cart.incrementQuantityByItemId(workingItemId); //购物车中已存在,数量+1

        } else {
            boolean isInStock = catalogService.isItemInStock(workingItemId);//检查存货
            ItemVO item = catalogService.getItem(workingItemId);
//            cart.addItem(item, isInStock);//有存货,加入此item
            if (!isInStock || inventoryService.getInventoryByItemId(workingItemId) <= 0) {
                return CommonResponse.createForError(ResponseCode.InventoryShortageSuccess.getCode(), "该商品库存不足");
            }

            cart.addItem(item, true);
//            inventoryService.decreaseInventory(workingItemId, 1);
        }

        cartService.updateCArtInfo(username,cart);
        return CommonResponse.createForSuccess(ResponseCode.AddItemToCartSuccess.getCode(),ResponseCode.AddItemToCartSuccess.getDescription());
    }

    @PutMapping
    public CommonResponse updateCart(Model model, HttpServletRequest req, HttpServletResponse resp, @PathVariable String username) {
        String AjaxItemId = req.getParameter("itemId");
        String AjaxQuantity = req.getParameter("quantity");

        //修改个数时失焦触发
        //
        if (AjaxItemId != null && AjaxQuantity != null) {
            cartService.updateCartInfo(username, AjaxItemId, AjaxQuantity);
            CartVO newcart = cartService.getCart(username);
            if (newcart != null) {
                model.addAttribute("cart", newcart);
                BigDecimal itemPrice = catalogService.getItem(AjaxItemId).getListPrice();
                BigDecimal itemTotal = itemPrice.multiply(new BigDecimal(AjaxQuantity));
                itemTotal.setScale(2, RoundingMode.HALF_UP);
                // 创建 DecimalFormat 对象，并指定格式模式
                DecimalFormat df = new DecimalFormat("$#,##0.00");
                String itemTotal_str = df.format(itemTotal);

                //更新修改后的总价钱
                BigDecimal subTotal = new BigDecimal(00.00);
                subTotal.setScale(2, RoundingMode.HALF_UP);
                Iterator<CartItemVO> cartItems2 = newcart.getAllCartItems();
                while (cartItems2.hasNext()) {
                    CartItemVO cartItem = (CartItemVO) cartItems2.next();
                    String itemId = cartItem.getItem().getItemId();
                    BigDecimal Price = cartItem.getItem().getListPrice();
                    Price = Price.multiply(new BigDecimal(cartItem.getQuantity()));
                    subTotal = subTotal.add(Price);
                }
                String subTotal_str = df.format(subTotal);

                Map<String, String> jsonResponse = new HashMap<>();
                jsonResponse.put("itemTotal", itemTotal_str);
                jsonResponse.put("subTotal", subTotal_str);

                return CommonResponse.createForSuccess(ResponseCode.UpdateCartSuccess.getCode(),ResponseCode.UpdateCartSuccess.getDescription());
            }
        }

            CartVO cartVO = cartService.getCart(username);
            model.addAttribute("cart", cartVO);
        return CommonResponse.createForSuccess(ResponseCode.UserEditSuccess.getCode(),ResponseCode.UserEditSuccess.getDescription());

    }

    @DeleteMapping
    public CommonResponse removeCartItem(Model model, HttpServletRequest req, HttpServletResponse resp, @PathVariable String username) {
//        CartVO cart = cartService.getCart(username);
//        cartService.updateCArtInfo(username, cart);
//        cart = cartService.getCart(username);
//
////        DecimalFormat df = new DecimalFormat("$#,##0.00");
////        String subTotal_str = df.format(cart.getSubTotal());
////        Map<String, String> jsonResponse = new HashMap<>();
////        jsonResponse.put("subTotal", subTotal_str);
//        return CommonResponse.createForSuccess(ResponseCode.DeleteItemFromCartSuccess.getCode(),ResponseCode.DeleteItemFromCartSuccess.getDescription(),cart);
        String workingItemId = req.getParameter("workingItemId");
        System.out.println(workingItemId);
        CartVO cart = cartService.getCart(username);
        ItemVO item = cart.removeItemById(workingItemId);

//        if (item == null) {
//            model.addAttribute("errorMsg", "Attempted to remove null CartItem from Cart.");
//            return "common/error";
//        } else {
        //Account loginAccount = (Account) session.getAttribute("loginAccount");
        //if (loginAccount != null) {
        cartService.updateCArtInfo(username, cart);
        //}
        //session.setAttribute("workingItemID", workingItemId);
        DecimalFormat df = new DecimalFormat("$#,##0.00");

        Map<String, String> jsonResponse = new HashMap<>();
        String subTotal_str = df.format(cart.getSubTotal());
        jsonResponse.put("subTotal", subTotal_str);

        //}
        model.addAttribute("cart",cart);

        return CommonResponse.createForSuccess(ResponseCode.DeleteItemFromCartSuccess.getCode(),ResponseCode.DeleteItemFromCartSuccess.getDescription());
    }


}

